/*global window, $, Util, RFB, */

"use strict";
var _wstInit;

(function () {
    var host,
        port,
        rfb,
        thingName = '',
        connectedThing = false,
        logLevel = 'warn',
        encryptConnection = false,
        viewOnly = false,
        vncPassword = '',
        tunnelingUrl = '',
        tunnelName = '',
        timeOut = 300000,
        showStatusMessages = false,
        // TunnelId needed for connection
        tunnelId = '';

    _wstInit = function (config) {
        host = config.host;
        port = config.port;

        thingName = config.thingName || thingName;
        connectedThing = config.connectedThing || connectedThing;
        logLevel = config.logLevel || logLevel;
        encryptConnection = config.encryptConnection || encryptConnection;
        viewOnly = config.viewOnly || viewOnly;
        vncPassword = config.vncPassword || vncPassword;
        tunnelingUrl = config.tunnelingUrl || tunnelingUrl;
        tunnelName = config.tunnelName || tunnelName;
        timeOut = config.timeOut || timeOut,
        showStatusMessages = config.showStatusMessages || showStatusMessages;

        // TunnelId is necessary for connection
        tunnelId = config.tunnelId || tunnelId;
    };

    function updateState(rfb, state, oldstate, msg) {
        var s = $('#noVNC_status'),
            sb = $('#noVNC_status_bar'),
            cad = $('#sendCtrlAltDelButton'),
            level;
        switch (state) {
            case 'failed':
                level = "error";
                break;
            case 'fatal':
                level = "error";
                break;
            case 'normal':
                level = "normal";
                break;
            case 'disconnected':
                level = "normal";
                break;
            case 'loaded':
                level = "normal";
                break;
            default:
                level = "warn";
                break;
        }

        if (state === "normal") {
            cad.prop('disabled', false);
        } else {
            cad.prop('disabled', true);
        }

        sb.removeClass().addClass("noVNC_status_" + level);
        if (showStatusMessages && msg) {
            s.text(msg);
        }
    }

    function connect(evt) {
        $("#noVNC_canvas").focus();
        if (connectedThing === false) {
            var path = tunnelingUrl + '/' + thingName + '&dest=' + tunnelName;
            rfb.connect(host, port, vncPassword, path);
            return;
        }

        // Determine how to establish a connection when tunnelId already exists
        if (tunnelId) {
            rfb.connect(host, port, vncPassword, tunnelingUrl + '/' + tunnelId);
        }
        $(evt.currentTarget).blur();
    }

    function sendCtrlAltDel(evt) {
        rfb.sendCtrlAltDel();
        $(evt.currentTarget).blur();
        return false;
    }

    function shutdown(evt) {
        rfb.disconnect();
        window.close();  
        return false;
    }

    $(document).ready(function () {
        WebUtil.init_logging(WebUtil.getQueryVar('logging', logLevel));

        // The address of the project deployment. I'm dead here. If there are cross-domain problems, they need to be solved.
        if (host.substring(0, 5) == 'https') {
            host = host.substr(8, host.length)
        }
        else if (host.substring(0, 4) == 'http') {
            host = host.substr(7, host.length)
        }

        rfb = new RFB({
            'target': $('#noVNC_canvas').get(0),
            'encrypt': encryptConnection,
            'repeaterID': '',
            'true_color': true,
            'local_cursor': true,
            'shared': true,
            'view_only': viewOnly,
            'onUpdateState': updateState
        });

        $('#connectButton').on('click', connect);
        $('#sendCtrlAltDelButton').on('click', sendCtrlAltDel);
        $('#shutdownButton').on('click', shutdown);
    });

}());

